package org.seamon.management.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.seamon.management.pojo.dto.MenuInsertDto;
import org.seamon.management.pojo.dto.MenuUpdateDto;
import org.seamon.management.service.MenuService;
import org.seamon.management.util.Result;
import org.seamon.management.util.aspect.Limit;
import org.seamon.management.util.aspect.Log;
import org.seamon.management.util.enums.BusinessTypeEnum;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

/**
 * @author Simon
 */
@Slf4j
@RestController
@RequestMapping("/api/menu")
public class MenuController {
    @Resource
    private MenuService menuService;

    @PreAuthorize("hasAuthority('menu:list')")
    @Log(title = "获取全部菜单树", businessType = BusinessTypeEnum.LIST)
    @GetMapping("/tree")
    public Result<?> tree() {
        log.debug("获取全部菜单树");
        return Result.success(menuService.tree());
    }

    @PreAuthorize("hasAuthority('menu:list')")
    @Log(title = "获取角色菜单树", businessType = BusinessTypeEnum.LIST)
    @GetMapping("/tree/{roleId}")
    public Result<?> tree(@PathVariable Long roleId) {
        log.debug("获取角色菜单树");
        return Result.success(menuService.tree(roleId));
    }

    @Limit(key = "menu_save", permitsPerSecond = 10, timeout = 1, timeunit = TimeUnit.SECONDS)
    @PreAuthorize("hasAuthority('menu:add')")
    @Log(title = "菜单保存", businessType = BusinessTypeEnum.ADD)
    @PostMapping()
    public Result<?> save(@RequestBody @Valid MenuInsertDto dto) {
        log.debug("保存菜单, {}", dto);
        menuService.save(dto);
        return Result.success();
    }

    @Limit(key = "menu_update", permitsPerSecond = 10, timeout = 1, timeunit = TimeUnit.SECONDS)
    @PreAuthorize("hasAuthority('menu:edit')")
    @Log(title = "菜单更新", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping()
    public Result<?> update(@RequestBody @Valid MenuUpdateDto dto) {
        log.debug("更新菜单, {}", dto);
        menuService.update(dto);
        return Result.success();
    }

    @Limit(key = "menu_delete", permitsPerSecond = 10, timeout = 1, timeunit = TimeUnit.SECONDS)
    @PreAuthorize("hasAuthority('menu:delete')")
    @Log(title = "菜单删除", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        log.debug("删除菜单, id: {}", id);
        menuService.removeById(id);
        return Result.success();
    }

}
